<template>
    <!-- 面包屑 -->
    <div>
        <el-breadcrumb separator="/">
            <el-breadcrumb-item :to="{ path: '/home' }" @click="setActivePath">首页</el-breadcrumb-item>
            <el-breadcrumb-item>权限管理</el-breadcrumb-item>
            <el-breadcrumb-item>用户列表</el-breadcrumb-item>
        </el-breadcrumb>
    </div>

    <el-card>

        <!-- 搜索添加用户 -->
        <el-row :gutter="60">
            <el-col :span="9">
                <el-input v-model="queryInfo.query" @clear="getUserList" placeholder="请输入用户名" clearable
                    style="width: 545px;height:40px">
                    <template #append>
                        <el-button :icon="Search" circle @click="getUserList" />
                    </template>
                </el-input>
            </el-col>

            <el-col :span="5">
                <el-button type="primary" @click="addUserBtn" style="height:40px">添加用户</el-button>
            </el-col>
        </el-row>

        <!-- 用户列表 -->
        <el-table :data="userList" border stripe style="margin-top: 20px;">
            <el-table-column type="index" /> <!--索引列-->
            <el-table-column prop="username" label="用户名" />
            <el-table-column prop="email" label="邮箱" />
            <!-- <el-table-column prop="password" label="密码" /> -->
            <el-table-column prop="roleNames" label="角色" />
            <el-table-column prop="state" label="状态">
                <template #default="scope">
                    <el-switch v-model="scope.row.state" @change="changeState(scope)" />
                </template>
            </el-table-column>
            <el-table-column label="操作">
                <template #default="scope">
                    <el-button type="primary" :icon="Edit" @click="editUser(scope)" circle />
                    <el-button type="danger" :icon="Delete" @click="deleteUser(scope.row.id,scope.row.roleNames)" circle />
                    <el-tooltip class="box-item" effect="dark" content="权限管理" placement="top">
                        <el-button type="warning" :icon="Setting" circle />
                    </el-tooltip>
                </template>
            </el-table-column>
        </el-table>

        <!-- 分页 -->
        <div class="page-div">
            <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :page-sizes="[4, 6, 8, 10]"
                size="default" :disabled="disabled" :background="background"
                layout="total, sizes, prev, pager, next, jumper" :total="total" @size-change="handleSizeChange"
                @current-change="handleCurrentChange" />
        </div>
    </el-card>

    <!-- 编辑对话框 -->
    <el-dialog v-model="centerDialogVisible" title="修改用户信息" width="500">
        <!-- 对话框主体 -->
        <el-form :model="dialogData" label-width="auto">
            <el-form-item label="用户名:">
                <el-input v-model="dialogData.username"  clearable disabled />
            </el-form-item>
            <el-form-item label="邮箱:">
                <el-input v-model="dialogData.email" placeholder="请输入邮箱" clearable />
            </el-form-item>
            <el-form-item label="修改密码:">
                <el-checkbox v-model="dialogData.changePassword"></el-checkbox>
            </el-form-item>
            <el-form-item>
            <el-input v-model="dialogData.password" placeholder="请输入新密码" v-if="dialogData.changePassword"
                style="margin-left:74px" type="password" clearable show-password/>
        </el-form-item>
        </el-form>
       
        <!-- 对话框页脚 -->
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="cancelEditUser">取消</el-button>
                <el-button type="primary" @click="saveEditUser">
                    保存
                </el-button>
            </div>
        </template>
    </el-dialog>

    <!-- 添加用户对话框 -->
    <el-dialog v-model="addDialogVisible" title="添加用户" width="500">
        <!-- 对话框主体 -->
        <el-form :model="addUserData" label-width="auto">
            <el-form-item label="用户名:">
                <el-input v-model="addUserData.username"  clearable />
            </el-form-item>
            <el-form-item label="密码:">
                <el-input v-model="addUserData.password"  type="password" clearable show-password/>
            </el-form-item>
            <el-form-item label="邮箱:">
                <el-input v-model="addUserData.email" clearable />
            </el-form-item>
            <el-form-item label="状态:">
                <el-input v-model="addUserData.state"  clearable />
            </el-form-item>
        </el-form>

        <!-- 对话框页脚 -->
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="cancelAddUser">取消</el-button>
                <el-button type="primary" @click="saveAddUser">
                    添加
                </el-button>
            </div>
        </template>
    </el-dialog>



</template>

<script setup>
import { Search, Edit, Setting, Delete } from '@element-plus/icons-vue'
import { ref, onMounted } from 'vue'
import { getUserListApi, changeUserStatusApi,deleteUserApi,updateUserApi} from '@/api/user'
import { ElMessage,ElMessageBox } from 'element-plus'

//搜索框数据
const queryInfo = ref({
    query: ''

})

//用户列表数据
const userList = ref([])
//前往的页码,当前页码
const currentPage = ref(1)
//页面条数
const pageSize = ref(6)
//分页条背景色
const background = ref(true)
//分页条是否可修改
const disabled = ref(false)
//总条数
const total = ref(0)

//编辑对话框是否可见
const centerDialogVisible = ref(false)
//添加用户对话框
const addDialogVisible=ref(false)

//编辑对话框数据
const dialogData = ref({
})
//添加对话框数据
const addUserData = ref({
})

/**
 * 添加用户按钮
 */
const addUserBtn=()=>{
    addDialogVisible.value=true
}
/** 
*获取用户列表
*/
const getUserList = async () => {
    try {
        const res = await getUserListApi(queryInfo.value.query, currentPage.value, pageSize.value)
        if (res.code !== 200) {
            ElMessage.error(res.msg)
            return
        } else {
            userList.value = res.data
            total.value = res.total
        }
    } catch (error) {
        console.error('获取用户列表失败:', error)
        ElMessage.error('获取用户列表失败')
    }
}

/**
 * 改变分页大小时调用
 */
const handleSizeChange = () => {
    getUserList()
}

/**
 *改变当前页码时调用 
 */
const handleCurrentChange = () => {
    getUserList()
}

/**
 * 钩子函数
 */
onMounted(() => {
    getUserList()
})

/**
 * 点击首页,清除激活路径
 */
const setActivePath = () => {
    sessionStorage.removeItem('activePath')// 清除激活路径
}

/**
 * 更改用户状态
 */
const changeState = async (scope) => {

    const { id, state ,roleNames} = scope.row
    try {
        const result = await changeUserStatusApi(id, state,roleNames)
        if (result.code !== 200) {
            ElMessage.error(result.msg || '操作失败')
            scope.row.state = !state
            return
        } else {
            ElMessage.success('操作成功')
        }
    } catch (error) {
        ElMessage.error('发送异常')
        scope.row.state = !state
    }
}

/**
 * 点击编辑用户按钮
 */
const editUser = (scope) => {
    //打开对话框
    centerDialogVisible.value = true;
    //填充对话框数据
    dialogData.value = scope.row
    //原密码不可见
    dialogData.value.password = ''
    //默认关闭修改密码
    dialogData.value.changePassword=false
}

/**
 * 取消编辑用户
 */
const cancelEditUser=()=>{
    //重置
    dialogData.value ={
        changePassword: false
    }
    //关闭对话框
    centerDialogVisible.value = false;
}

/**
 * 保存编辑用户
 */
const saveEditUser =async () => {

    const result = await updateUserApi(  dialogData.value.id,dialogData.value.email,dialogData.value.password);
        if (result.code === 200) {
            ElMessage.success('编辑成功!');
            //重新获取用户列表
            getUserList();
            //重置对话框数据
            dialogData.value = {
                changePassword: false
            }
            //关闭对话框
            centerDialogVisible.value = false;
        } else {
            ElMessage.error(result.msg||'更新失败');
        }
      
}

/**
 * 删除用户
 */
const deleteUser =async (id,roleNames) => { 
    //是否确定删除
    ElMessageBox.confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    })
    .then(async ()=>{
        //调用删除接口
        const result = await deleteUserApi(id,roleNames);
        if (result.code === 200) {
            ElMessage.success('删除成功!');
            //重新获取用户列表
            getUserList();
        } else {
            ElMessage.error(result.msg||'删除失败');
        }
    })
    .catch((err)=>{
        ElMessage.info(err||'取消删除');
    })
}


</script>

<style lang="less" scoped>
//面包屑样式
.el-breadcrumb {
    margin-bottom: 15px;
    font-size: 17px;
}

//分页条样式
.page-div {
    margin-top: 20px
}
</style>